﻿using System;
using System.IO;
using System.ComponentModel;
using ProtoBuf;

namespace Hotfix
{
    /// <summary>
    /// Proto工具(提供Socket的数据转换 object TO Bytes || Byte TO objcet)
    /// </summary>
    public static class ProtobufHelper
    {
        /// <summary>
        /// 将对象转换为Byte字节数组
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] GetBytes(object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                Serializer.Serialize(ms, obj);
                return ms.ToArray();
            }
        }

        /// <summary>
        /// 将一个字节数组转换为一个对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="dataBytes"></param>
        /// <param name="index"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static object FromBytes(Type type, byte[] dataBytes, int index, int length)
        {
            object obj;
            using (MemoryStream ms = new MemoryStream(dataBytes, index, length))
            {
                obj = Serializer.Deserialize(type, ms);
            }
            ISupportInitialize supportInitialize = obj as ISupportInitialize;

            if (supportInitialize == null)
                return obj;
            supportInitialize.EndInit();
            return obj;
        }
        /// <summary>
        /// 字节数组转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataBytes"></param>
        /// <returns></returns>
        public static T FromBytes<T>(byte[] dataBytes)
        {
            T t;
            using (MemoryStream ms = new MemoryStream(dataBytes))
            {
                t = Serializer.Deserialize<T>(ms);
            }
            ISupportInitialize supportInitialize = t as ISupportInitialize;

            if (supportInitialize == null)
                return t;

            supportInitialize.EndInit();
            return t;
        }

        /// <summary>
        /// 字节数组转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataBytes"></param>
        /// <param name="index"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static T FromBytes<T>(byte[] dataBytes, int index, int length)
        {
            T t;
            using (MemoryStream ms = new MemoryStream(dataBytes, index, length))
            {
                t = Serializer.Deserialize<T>(ms);
            }
            ISupportInitialize supportInitialize = t as ISupportInitialize;

            if (supportInitialize == null)
                return t;

            supportInitialize.EndInit();
            return t;
        }
    }
}
